/* eslint-disable react/jsx-no-bind */
/* eslint-disable max-lines-per-function */
import React, {useState, useEffect, useCallback} from 'react';
import {withRouter} from 'react-router-dom';
import moment from 'moment';
import {ArrowLeftOutlined, PlusOutlined} from '@ant-design/icons';
import {Form} from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
    Card,
    Select,
    DatePicker,
    Radio,
    Input,
    Divider,
    Button,
    Row,
    Col,
    InputNumber,
    notification,
    message,
} from 'antd';
import {debounce} from 'lodash';
import popUpContainer from '~/utils/common/popupFix';
import {getDept, getChannel, createAdv, advDetail, updateAdv, getCategory} from '~/service/sales';
import './index.styl';
import format from '../format';

const {Option} = Select;
const {RangePicker} = DatePicker;
const debounceWaitTime = 500;
// 群类别全量，提交时查找使用
let allCategoryMap = new Map();
function NewAdv(props) {
    const {
        form: {
            getFieldDecorator,
            validateFields,
            setFieldsValue,
            resetFields,
        },
        location: {search: searchString}
    } = props;

    const searchParams = new URLSearchParams(searchString);
    const id = searchParams.get('id');
    const type = searchParams.get('type');

    const [showTail, setShowTail] = useState(false);
    const [department, setDepartment] = useState();
    const [depList, setDepList] = useState([]);
    const [saving, setSaving] = useState(false);
    // 渠道
    const [channel, setChannel] = useState();
    const [channelList, setChannelList] = useState([]);
    const [isAdvPrice, setIsAdvPrice] = useState(true);
    const [tailRatio, setTailRatio] = useState();
    const [showTailRatio, setShowTailRatio] = useState(true);

    // 群类别选项
    const [categoryMap, setCategoryMap] = useState(new Map());
    const [tailCategoryMap, setTailCategoryMap] = useState(new Map());

    const adultReg = /成人/;
    // dept选项
    useEffect(() => {
        getDept().then(res => {
            setDepList(res.data.departmentList);
            // 设置默认dept 新建时才自动设置
            if (type !== 'edit' && res.data.departmentList.length > 0) {
                setDepartment(res.data.departmentList[0]);
                setFieldsValue({
                    department: res.data.departmentList[0]
                });
            }
        });
    }, []);

    // 编辑逻辑
    useEffect(() => {
        if (type === 'edit') {
            advDetail({id}).then(res => {
                if (res) {
                    // 是否有尾量
                    setShowTail(res.data.tailBeginTime);
                    // 是否多用户投放成本
                    setIsAdvPrice(+res.data.priceType === 1);

                    const fields = {
                        ...res.data,
                        advTime: [
                            moment(res.data.advBeginTime, format.DATE_FORMAT),
                            moment(res.data.advEndTime, format.DATE_FORMAT)
                        ],
                        tailAdvTime: [
                            moment(res.data.tailBeginTime, format.DATE_FORMAT),
                            moment(res.data.tailEndTime, format.DATE_FORMAT)
                        ],
                        singleCost: +(res.data.singleCost / 100).toFixed(2),
                        advPrice: +(res.data.advPrice / 100).toFixed(2),
                    };
                    if (res.data.chatroomCategoryList) {
                        // 设置表单值
                        fields.chatroomCategoryList = res.data.chatroomCategoryList.map(e => e.id);
                        // 设置cateMap，选项
                        const categoryMap = parseListToMap(res.data.chatroomCategoryList);
                        setCategoryMap(categoryMap);

                        // 设置全量category
                        allCategoryMap = new Map([...allCategoryMap, ...categoryMap]);
                    }
                    if (res.data.tailCategoryIdList) {
                        fields.tailCategoryIdList = res.data.tailCategoryIdList.map(e => e.id);

                        const categoryMap = parseListToMap(res.data.tailCategoryIdList);
                        setTailCategoryMap(categoryMap);
                        // 设置全量category 也需要包含尾量的category选项
                        allCategoryMap = new Map([...allCategoryMap, ...categoryMap]);
                    }
                    if (res.data.department) {
                        setDepartment(res.data.department);
                    }
                    setFieldsValue(fields);
                }
            })
                .catch(errObj => {
                    message.error(errObj.msg);
                });
        }
    }, [id, type]);

    useEffect(() => {
        if (department) {
            getChannel(department).then(res => {
                setChannelList(res.data.channelList);
            });
        }
    }, [department]);

    useEffect(() => {
        // 渠道类型控制成本展示
        for (const e of channelList) {
            if (e.name === channel) {
                // 1 外部渠道 2 内部渠道
                setIsAdvPrice(+e.type === 1);
                if (+e.type === 2) {
                    // 当投放渠道选择“内部渠道”时，涓流系数隐藏不显示,并且默认为1。
                    setShowTailRatio(false);
                }
                else {
                    setShowTailRatio(true);
                }
            }
        }
    }, [channel]);

    function clearShowTail() {
        setShowTail(false);
        // reset tail fields
        setFieldsValue({
            tailAdvTime: null,
            tailRatio: null,
            tailCategoryIdList: null
        });
    }

    function gobackToList() {
        const {history} = props;
        const {location: {pathname}} = history;
        // 避免用户切换页面后无谓的跳转
        if (pathname === '/sales/haoke/create') {
            history.goBack();
        }
    }

    function showNoti() {
        const key = `noti${Date.now()}`;
        const btn = (
            <Button
                type="primary"
                size="small"
                onClick={() => {
                    notification.close(key);
                }}
            >
                知道了
            </Button>
        );
        const notiObj = {
            message: '数据计算中',
            description: '群人数，单用户成本等数据会在投放截止时间1小时后计算得出，请耐心等待！同时您可以在列表页点击刷新数据查看数据是否计算完成。',
            duration: 3,
            btn,
            key,
        };
        notification.open(notiObj);
    }

    function handleSave(e) {
        e.preventDefault();
        saveValidateAdv(() => {
            showNoti();
            gobackToList();
        });
    }
    function handleNext(e) {
        e.preventDefault();
        saveValidateAdv(() => {
            showNoti();
        });
    }

    function saveValidateAdv(callback) {
        validateFields((errObj, values) => {
            if (!errObj) {
                const param = {
                    ...values,
                    advBeginTime: values.advTime[0].format('YYYY-MM-DD HH:00'),
                    advEndTime: values.advTime[1].format('YYYY-MM-DD HH:00'),
                    // 后端加的字段, 1总额，2：单用户
                    priceType: isAdvPrice ? 1 : 2
                };

                // 尾量起止时间
                if (values.tailAdvTime) {
                    // 尾量时间检查
                    if (values.tailAdvTime[0] < values.advTime[1]) {
                        message.error('尾量开始时间需要晚于投放结束时间');
                        return;
                    }

                    param.tailBeginTime = values.tailAdvTime[0].format('YYYY-MM-DD HH:00');
                    param.tailEndTime = values.tailAdvTime[1].format('YYYY-MM-DD HH:00');
                }

                // 金额单位为 分
                if (isAdvPrice) {
                    param.advPrice = Math.floor(+values.advPrice * 100);
                }
                else {
                    param.singleCost = Math.floor(+values.singleCost * 100);
                }

                // 内部渠道涓流系数 默认1
                if (!showTailRatio) {
                    param.tailRatio = 1;
                }

                // 群类别
                if (values.chatroomCategoryList) {
                    param.chatroomCategoryList = values.chatroomCategoryList.map(id => ({
                        id,
                        name: allCategoryMap.get(id)
                    }));
                }

                if (values.tailCategoryIdList) {
                    param.tailCategoryIdList = values.tailCategoryIdList.map(id => ({
                        id,
                        name: allCategoryMap.get(id)
                    }));
                }

                setSaving(true);
                if (type === 'edit') {
                    param.id = id;
                    updateAdv(param).then(res => {
                        // 提交成功后，清空项目
                        resetFields();
                        // 编辑时提交成功后，replace history
                        if (type === 'edit') {
                            props.history.replace('/sales/haoke/create');
                        }
                        if (callback) {
                            callback(res);
                        }
                    })
                        .catch(errObj => {
                            message.error(errObj.msg);
                        })
                        .finally(() => {
                            setSaving(false);
                        });
                }
                else {
                    createAdv(param).then(res => {
                        // 提交成功后，清空项目
                        resetFields();
                        if (callback) {
                            callback(res);
                        }
                    })
                        .catch(errObj => {
                            message.error(errObj.msg);
                        })
                        .finally(() => {
                            setSaving(false);
                        });
                }
            }
        });
    }

    function changeChannel(value) {
        setChannel(value);
    }

    function deptChange(e) {
        // 涓流系数的默认值根据学部变化
        switch (e) {
            case '高中':
                setTailRatio(0.5);
                break;
            case '初中':
                setTailRatio(0.3);
                break;
            default:
                setTailRatio('');
                break;
        }
        setDepartment(e);
        // 手动修改department时 需要清空channel
        resetFields(['channel']);
    }

    const debounceFetchCategory = useCallback(debounce(fetchCategoryList, debounceWaitTime, {
        leading: false
    }), []);

    function fetchCategoryList(keyword = '') {
        getCategory({
            keyword
        }).then(res => {
            // 新的map需要加上已选择的选项
            const newCategoryMap = parseListToMap(res.data.categoryList);
            // 向两个map中均添加选项，保持最新
            setCategoryMap(newCategoryMap);
            setTailCategoryMap(newCategoryMap);

            // 设置全量category
            allCategoryMap = new Map([...allCategoryMap, ...newCategoryMap]);
        })
            .catch(errObj => {
                message.error(errObj.msg);
            });
    }

    return (
        <Card
            title={(
                <>
                    <ArrowLeftOutlined onClick={gobackToList} style={{marginRight: '5px'}} />
                    投放填报
                </>
            )}
            className="newAdv"
        >
            <Form onSubmit={handleSave} labelCol={{span: 6}} wrapperCol={{span: 10}}>
                <Form.Item label="学部">
                    {
                        getFieldDecorator('department', {
                            rules: [
                                {
                                    required: true,
                                    message: '请选择学部',
                                },
                            ],
                        })(
                            <Select
                                placeholder="请选择学部"
                                onChange={deptChange}
                                getPopupContainer={popUpContainer}
                            >
                                {
                                    depList.map(item => (
                                        <Option key={item} value={item} title={item}>
                                            {item}
                                        </Option>
                                    ))
                                }
                            </Select>
                        )
                    }
                </Form.Item>
                <Form.Item label="投放起止时间">
                    {
                        getFieldDecorator('advTime', {
                            rules: [{type: 'array', required: true, message: '请输入投放起止时间'}],
                        })(
                            <RangePicker
                                showTime={{format: 'HH'}}
                                format="YYYY-MM-DD HH:00"
                                style={{
                                    width: '100%'
                                }}
                            />
                        )
                    }
                </Form.Item>
                <Form.Item label="渠道分类">
                    {
                        getFieldDecorator('channel', {
                            rules: [{required: true, message: '请选择渠道分类'}],
                        })(
                            <Select
                                placeholder="请选择渠道分类"
                                onChange={changeChannel}
                                getPopupContainer={popUpContainer}
                            >
                                {
                                    channelList.map(item => (
                                        <Option key={item.name} value={item.name}>
                                            {item.name}
                                        </Option>
                                    ))
                                }
                            </Select>
                        )
                    }
                </Form.Item>
                <Form.Item label="群类别">
                    {
                        getFieldDecorator('chatroomCategoryList', {
                            rules: [{required: true, message: '请选择群类别'}],
                        })(
                            <Select
                                allowClear
                                autoClearSearchValue={false}
                                filterOption={false}
                                placeholder="请选择群类别"
                                mode="multiple"
                                getPopupContainer={popUpContainer}
                                onFocus={fetchCategoryList}
                                onSearch={debounceFetchCategory}
                            >
                                {
                                    [...categoryMap.keys()].map(key => (
                                        <Option key={key} value={key}>
                                            {categoryMap.get(key)}
                                        </Option>
                                    ))
                                }
                            </Select>
                        )
                    }
                </Form.Item>
                <Form.Item label="是否计入成本">
                    {getFieldDecorator('canCost', {
                        initialValue: 1,
                        rules: [{required: true, message: '请输入是否计入成本'}],
                    })(
                        <Radio.Group>
                            <Radio value={1}>是</Radio>
                            <Radio value={0}>否</Radio>
                        </Radio.Group>
                    )}
                </Form.Item>
                {isAdvPrice ? (
                    <Form.Item label="投放成本">
                        <span style={{marginRight: '5px'}}>￥</span>
                        {getFieldDecorator('advPrice', {
                            initialValue: '',
                            rules: [
                                {required: true, message: '请输入投放成本'},
                                {pattern: /^\d+(\.\d{0,2})?$/, message: '请输入最多2位小数'}
                            ],
                        })(<InputNumber
                            placeholder="请输入投放成本"
                            style={{
                                width: '200px'
                            }}
                        />)}
                    </Form.Item>
                ) : (
                    <Form.Item label="单用户成本">
                        <span style={{marginRight: '5px'}}>￥</span>
                        {getFieldDecorator('singleCost', {
                            initialValue: '',
                            rules: [
                                {required: true, message: '请输入单用户成本'},
                                {pattern: /^\d+(\.\d{0,2})?$/, message: '请输入最多2位小数'}
                            ],
                        })(<InputNumber
                            placeholder="请输入单用户成本"
                            style={{
                                width: '200px'
                            }}
                        />)}
                    </Form.Item>
                )}
                {adultReg.test(department)
                    ? ''
                    : showTail ? (
                        <>
                            <Divider dashed />
                            <Form.Item label="尾量投放填报">
                                <Button type="primary" onClick={clearShowTail}>删除</Button>
                            </Form.Item>
                            <Form.Item label="尾量起止时间">
                                {
                                    getFieldDecorator('tailAdvTime', {
                                        rules: [{type: 'array', required: true, message: '请输入尾量起止时间'}],
                                    })(
                                        <RangePicker
                                            showTime={{format: 'HH'}}
                                            format="YYYY-MM-DD HH:00"
                                            style={{
                                                width: '100%'
                                            }}
                                        />
                                    )
                                }
                            </Form.Item>
                            {showTailRatio
                            && (
                                <Form.Item label="涓流系数">
                                    {getFieldDecorator('tailRatio', {
                                        initialValue: tailRatio,
                                        rules: [
                                            {required: true, message: '请输入涓流系数'},
                                            {pattern: /^1$|^0($|.\d*)/, message: '小于等于1的小数'}
                                        ],
                                    })(<InputNumber
                                        placeholder="请输入涓流系数"
                                        style={{
                                            width: '120px'
                                        }}
                                    />)}
                                </Form.Item>
                            )
                            }
                            <Form.Item label="涓流群类别">
                                {getFieldDecorator('tailCategoryIdList', {
                                    rules: [{required: true, message: '请选择涓流群类别'}],
                                })(
                                    <Select
                                        allowClear
                                        autoClearSearchValue={false}
                                        filterOption={false}
                                        placeholder="请选择涓流群类别"
                                        mode="multiple"
                                        getPopupContainer={popUpContainer}
                                        onFocus={fetchCategoryList}
                                        onSearch={debounceFetchCategory}
                                    >
                                        {
                                            [...tailCategoryMap.keys()].map(key => (
                                                <Option key={key} value={key}>
                                                    {allCategoryMap.get(key)}
                                                </Option>
                                            ))
                                        }
                                    </Select>
                                )}
                            </Form.Item>
                        </>
                    ) : (
                        <Row>
                            <Col span={10} offset={6}>
                                <Button
                                    type="dashed" onClick={() => {
                                        setShowTail(true);
                                    }}
                                >
                                    <PlusOutlined />
                                    尾量投放填报
                                </Button>
                            </Col>
                        </Row>
                    )
                }
            </Form>
            <Divider />
            <div className="funcs">
                <Button onClick={gobackToList}>取消</Button>
                <Button type="primary" onClick={handleSave} loading={saving}>保存</Button>
                <Button type="primary" onClick={handleNext} loading={saving}>保存并填写下一组</Button>
            </div>
        </Card>
    );
}

/**
 * obj list -> map
 * @param {Array<{id, name}>} list
 */
function parseListToMap(list) {
    const newMap = new Map();
    if (list && list.length > 0) {
        list.forEach(ele => {
            newMap.set(ele.id, ele.name);
        });
    }
    return newMap;
}

export default Form.create({name: 'newAdv'})(withRouter(NewAdv));
